package com.webapp.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.webapp.domain.entity.Disputes;
import com.webapp.domain.entity.Mediation;
import com.webapp.domain.vo.Pagination;
@Repository("mediationDAO")
public class MediationDAO extends AbstractDAO<Mediation> {

	public List<Mediation> getMediationAll(){
		return this.loadAll();
	}
	/**
	 * 分页查询纠纷咨询列表
	 * @param messageQuery	获取未读消息的条件
	 * @param whereQuery	查询纠纷的条件
	 * @param p
	 * @return
	 */
	public Pagination<Disputes> paginateByQuery(String messageQuery, 
			String whereQuery,Pagination<Disputes> p){
		List<Disputes> result=new ArrayList<Disputes>();
		Long count = getCount("select count(*) from Disputes d "+whereQuery);
		p.setTotalCount(count);
		String hql = "select d," +
				"(select count(*) from Message m left join m.session s"
				+ " where s.disputes.id=d.id "+messageQuery+") as number"
				+ " from Disputes d "
				+ " left join fetch d.disputesData "
				+ " left join fetch d.proposer "
				+ " left join fetch d.arbdic "
				+ " left join fetch d.evaluate "
				+ " left join fetch d.mediation m"
				+whereQuery;
		if(!StringUtils.isEmpty(p.getDirection())){
			if ("desc".equals(p.getDirection())) {
				hql = hql + " order by m."+p.getOrderBy()+" desc";
			}else {
				hql = hql + " order by m."+p.getOrderBy();
			}
		}
		Query query = getSession().createQuery(hql).setFirstResult(p.getPosStart())
				.setMaxResults(p.getPageSize());
		List<Object[]> d = query.list();
		Disputes temp;
		for (Object[] object : d) {
			temp=(Disputes)object[0];
			temp.setMessageCount((Long)object[1]);
			result.add(temp);
		}
		p.setData(result);
		return p;
	}
	
	
	/**
	 * 执行sql，返回long
	 * @param countHql
	 * @return
	 */
	public Long getCount(String countHql){
		Object object = getSession().createQuery(countHql).uniqueResult();
		return (Long)object;
	}
	
}
